package com.lcf.transaction;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.interceptor.DefaultTransactionAttribute;

/**
 * Created by Administrator on 2019/4/28.
 *
 * @Scope("prototype")，每个事务都是新的实例，解决线程安全问题
 */
@Component
@Scope("prototype")
public class TransactionUtils {

    @Autowired
    private DataSourceTransactionManager transactionManager;

    private TransactionStatus transactionStatus;

    //开启事务
    public TransactionStatus begin() {
        //设置事务默认传播级别
        TransactionStatus transactionStatus = transactionManager.getTransaction(new DefaultTransactionAttribute());
        return transactionStatus;
    }

    //提交事务
    public void commit(TransactionStatus transactionStatus) {
        transactionManager.commit(transactionStatus);
    }

    //事务回滚
    public void rollback() {
        System.out.println("回滚事务.....");
        transactionManager.rollback(transactionStatus);
    }
}
